import turtle as t
import random as r
points = [[0, 20],[0,0],[0,-20]]
dis = 20
index = 1
coors = []
is_delete = True
def draw():
    t.clear()
    for i in range(len(points)):
        t.up()
        t.goto(points[i])
        t.down()
        t.dot(20, "red")
    for coor in coors:
        t.up()
        t.goto(coor)
        t.down()
        t.dot(20, 'cyan')
    move()
    t.ontimer(draw, 300)

def food():
    for i in range(4):
        coor = [r.randint(-320, 320), r.randint(-320, 320)]
        coors.append(coor)

def move():
    global is_delete
    point = points[0].copy()
    for i in range(len(coors)):
        coor = coors[i]
        if abs(point[0]-coor[0])<20 and abs(point[1]-coor[1])<20:
            coors[i] = [r.randint(-320, 320), r.randint(-320, 320)]
            break
    else:
        if is_delete:
            del points[-1]
        else:
            is_delete = True

    point[index] += dis
    points.insert(0, point)

def func_up():
    global  dis, index
    index = 1
    dis = 20
def func_down():
    global dis, index
    index = 1
    dis = -20
def func_left():
    global dis, index
    dis = -20
    index = 0

def func_right():
    global dis, index
    dis = 20
    index = 0

def func_click(x,y):
    global is_delete
    is_delete = False

if __name__ == '__main__':
    t.tracer(False)
    food()
    draw()
    t.onkeypress(func_down, "Down")
    t.onkeypress(func_up, "Up")
    t.onkeypress(func_left, "Left")
    t.onkeypress(func_right, "Right")
    t.listen()
    t.onscreenclick(func_click)
    t.done()